package com.tanhua.app.controller;

import com.tanhua.app.interceptor.UserHolder;
import com.tanhua.app.service.UserService;
import com.tanhua.commons.utils.JwtUtils;
import com.tanhua.model.pojo.UserInfo;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;
    //发送验证码
    @PostMapping("/login")
    public ResponseEntity login(@RequestBody Map map){
        //1.获取手机号
        String phone = (String) map.get("phone");
        //2.发送验证码
        userService.sendCode(phone);
        //3.返回数据
        return ResponseEntity.ok(null);
    }

    //用户登录功能
    @PostMapping("/loginVerification")
    public ResponseEntity loginVerification(@RequestBody Map map){
        //获取用户手机号和验证码
        String phone = (String) map.get("phone");
        String codes = (String) map.get("verificationCode");
        //调用userService完成登录
        Map retMap = userService.loginVerification(phone,codes);
        //返回结果
        return ResponseEntity.ok(retMap);
    }

    //用户首次登录完善资料
    @PostMapping("/loginReginfo")
    public ResponseEntity loginReginfo(@RequestBody UserInfo userInfo,@RequestHeader("Authorization") String token){
        //1.判断token是否合法
        boolean verifyToken = JwtUtils.verifyToken(token);
        if (!verifyToken) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(null);
        }
        //2.向userInfo中设置Id,调用service层方法
        Claims claims = JwtUtils.getClaims(token);
        Long id =  Long.parseLong(claims.get("id").toString());
        //Long userId = UserHolder.getUserId();
        userInfo.setId(id);
        //3.返回结果
        userService.loginReginfo(userInfo);
        return ResponseEntity.ok(null);
    }

    //用户首次登录上传头像
    @PostMapping("/loginReginfo/head")
    public ResponseEntity head(MultipartFile headPhoto,@RequestHeader("Authorization") String token) throws IOException {
        //1.判断token是否合法
        boolean verifyToken = JwtUtils.verifyToken(token);
        if (!verifyToken) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(null);
        }
        //2.获取用户id
        Claims claims = JwtUtils.getClaims(token);
        Long id =  Long.parseLong(claims.get("id").toString());
        //Long id = UserHolder.getUserId();
        //3.调用service
        userService.updateHead(headPhoto,id);
        //4.返回结果
        return ResponseEntity.ok(null);
    }
}
